<template>
  <div class="assessment-list-container">
    <div class="header">
      <h1>心理测评</h1>
      <p>请选择一个测评开始</p>
    </div>

    <div class="assessment-list">
      <div
        v-for="assessment in paginatedAssessments"
        :key="assessment.id"
        class="assessment-card"
        @click="startAssessment(assessment.id)"
      >
        <div class="assessment-icon">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M12 15V12M12 8H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </div>
        <h3 class="assessment-title">{{ assessment.title }}</h3>
        <p class="assessment-description">{{ assessment.description }}</p>
        <div class="assessment-meta">
          <span class="duration">{{ assessment.duration }}分钟</span>
          <span class="question-count">{{ assessment.questionCount }}题</span>
        </div>
        <button class="start-button">开始测评</button>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="totalPages > 1" class="pagination">
      <button class="pagination-btn" @click="prevPage" :disabled="currentPage === 1">
        上一页
      </button>
      <div class="pagination-numbers">
        <button
          v-for="page in totalPages"
          :key="page"
          class="pagination-number"
          :class="{ active: page === currentPage }"
          @click="goToPage(page)"
        >
          {{ page }}
        </button>
      </div>
      <button class="pagination-btn" @click="nextPage" :disabled="currentPage === totalPages">
        下一页
      </button>
    </div>

    <div class="my-results">
      <h2>我的测评结果</h2>
      <div v-if="myResults.length > 0" class="results-list">
        <div
          v-for="result in myResults"
          :key="result.id"
          class="result-card"
          @click="viewResult(result.id)"
        >
          <div class="result-card-header">
            <h4>{{ result.assessmentTitle }}</h4>
            <button class="delete-button" @click.stop="deleteResult(result.id)">删除</button>
          </div>
          <p>完成时间: {{ formatDate(result.completedAt) }}</p>
          <span class="result-score">得分: {{ result.totalScore }}</span>
        </div>
      </div>
      <div v-else class="no-results">
        <p>您还没有完成任何测评</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { assessmentAPI, resultAPI } from '@/utils/api'
import { useUserStore } from '@/stores/user'

export default {
  name: 'AssessmentListView',
  setup() {
    const router = useRouter()
    const userStore = useUserStore()
    const assessments = ref([])
    const myResults = ref([])
    const loading = ref(false)
    const error = ref('')
    const currentPage = ref(1)
    const pageSize = ref(3)

    // 获取测评列表
    const fetchAssessments = async () => {
      loading.value = true
      error.value = ''
      try {
        const response = await assessmentAPI.getAssessments()
        // 模拟数据，因为实际API可能返回的结构不同
        if (!response.length) {
          // 如果API返回空数组，使用模拟数据
          assessments.value = [
            {
              id: 1,
              title: '中学生心理健康量表',
              description: '评估中学生心理健康状况，包括考试焦虑、学业压力等多个维度',
              duration: 30,
              questionCount: 60,
            },
            {
              id: 2,
              title: '心理测试题库',
              description: '全面的心理健康测评，包括焦虑、抑郁等常见心理问题评估',
              duration: 20,
              questionCount: 50,
            },
            {
              id: 3,
              title: '职业兴趣测评',
              description: '帮助您了解自己的职业兴趣倾向',
              duration: 15,
              questionCount: 30,
            },
            {
              id: 4,
              title: '性格特质评估',
              description: '评估您的性格特质和优势劣势',
              duration: 15,
              questionCount: 25,
            },
          ]
        } else {
          assessments.value = response
        }
      } catch (err) {
        error.value = '获取测评列表失败'
        console.error('Failed to fetch assessments:', err)
        // 使用模拟数据作为后备
        assessments.value = [
          {
            id: 1,
            title: '中学生心理健康量表',
            description: '评估中学生心理健康状况，包括考试焦虑、学业压力等多个维度',
            duration: 30,
            questionCount: 60,
          },
          {
            id: 2,
            title: '心理测试题库',
            description: '全面的心理健康测评，包括焦虑、抑郁等常见心理问题评估',
            duration: 20,
            questionCount: 50,
          },
          {
            id: 3,
            title: '职业兴趣测评',
            description: '帮助您了解自己的职业兴趣倾向',
            duration: 15,
            questionCount: 30,
          },
          {
            id: 4,
            title: '性格特质评估',
            description: '评估您的性格特质和优势劣势',
            duration: 15,
            questionCount: 25,
          },
        ]
      } finally {
        loading.value = false
      }
    }

    // 获取用户的测评结果
    const fetchMyResults = async () => {
      try {
        // 对于未登录用户，使用默认用户ID获取结果（可以从localStorage获取最近的resultId）
        const lastResultId = localStorage.getItem('lastResultId')
        
        if (userStore.isAuthenticated) {
          // 登录用户通过API获取所有结果
          const response = await resultAPI.getResults()
          if (!response.length) {
            myResults.value = []
          } else {
            // 转换每个结果的字段名称以匹配模板期望
            myResults.value = response.map(result => ({
              id: result.id,
              assessmentTitle: result.assessmentTitle || '心理测评',
              completedAt: result.createdAt || new Date().toISOString(),
              totalScore: result.score || 0
            }))
          }
        } else if (lastResultId) {
          // 未登录用户，尝试获取最近的测评结果
          try {
            const response = await resultAPI.getResultById(lastResultId)
            // 将单个结果转换为数组格式并转换字段名称以匹配模板期望
            myResults.value = [{
              id: response.id,
              assessmentTitle: response.assessmentTitle || '心理测评',
              completedAt: response.createdAt || new Date().toISOString(),
              totalScore: response.score || 0
            }]
          } catch (err) {
            console.error('Failed to fetch last result:', err)
            myResults.value = []
          }
        } else {
          // 如果没有登录也没有最近的resultId，显示空结果
          myResults.value = []
        }
      } catch (err) {
        console.error('Failed to fetch results:', err)
        myResults.value = []
      }
    }

    // 开始测评
    const startAssessment = (assessmentId) => {
      router.push(`/assessment/${assessmentId}`)
    }

    // 查看测评结果
    const viewResult = (resultId) => {
      router.push(`/assessment/result/${resultId}`)
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 删除测评结果
    const deleteResult = async (resultId) => {
      if (confirm('确定要删除这个测评结果吗？删除后将无法恢复。')) {
        try {
          // 调用resultAPI删除结果
          await resultAPI.deleteResult(resultId)
          
          // 从列表中移除已删除的结果
          myResults.value = myResults.value.filter(result => result.id !== resultId)
          
          // 显示成功提示
          alert('测评结果已成功删除')
          
          // 如果删除的是最后一个查看的结果，清除localStorage中的记录
          const lastResultId = localStorage.getItem('lastResultId')
          if (lastResultId === resultId.toString()) {
            localStorage.removeItem('lastResultId')
          }
        } catch (err) {
          console.error('删除测评结果失败:', err)
          alert('删除测评结果失败，请稍后重试')
        }
      }
    }

    // 计算当前页显示的测评
    const paginatedAssessments = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      return assessments.value.slice(startIndex, endIndex)
    })

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(assessments.value.length / pageSize.value)
    })

    // 上一页
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
      }
    }

    // 下一页
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++
      }
    }

    // 跳转到指定页
    const goToPage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
        currentPage.value = page
      }
    }

    onMounted(() => {
      fetchAssessments()
      fetchMyResults()
    })

    return {
      assessments,
      paginatedAssessments,
      myResults,
      loading,
      error,
      currentPage,
      totalPages,
      startAssessment,
      viewResult,
      formatDate,
      deleteResult,
      prevPage,
      nextPage,
      goToPage
    }
  },
}
</script>

<style scoped>
.assessment-list-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 40px;
}

.header h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 10px;
}

.header p {
  font-size: 16px;
  color: #666;
}

.assessment-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto 40px;
}

.assessment-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.assessment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
  border-color: #61dafb;
}

.assessment-icon {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #61dafb 0%, #4fc0e8 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  color: white;
}

.assessment-icon svg {
  width: 30px;
  height: 30px;
}

.assessment-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.assessment-description {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.assessment-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  font-size: 12px;
  color: #999;
}

.start-button {
  width: 100%;
  background: linear-gradient(135deg, #61dafb 0%, #4fc0e8 100%);
  color: white;
  border: none;
  padding: 12px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s ease;
}

.start-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(97, 218, 251, 0.3);
}

.my-results {
  max-width: 1200px;
  margin: 0 auto;
}

.my-results h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.results-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.result-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.result-card h4 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.result-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.delete-button {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: #c0392b;
}

.result-card p {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.result-score {
  font-size: 14px;
  font-weight: bold;
  color: #61dafb;
}

.no-results {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 16px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 30px 0;
  gap: 10px;
}

.pagination-btn {
  background-color: white;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #61dafb;
  color: white;
  border-color: #61dafb;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.pagination-numbers {
  display: flex;
  gap: 5px;
}

.pagination-number {
  background-color: white;
  border: 1px solid #ddd;
  width: 36px;
  height: 36px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination-number:hover {
  border-color: #61dafb;
  color: #61dafb;
}

.pagination-number.active {
  background-color: #61dafb;
  color: white;
  border-color: #61dafb;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .assessment-list {
    grid-template-columns: 1fr;
  }

  .results-list {
    grid-template-columns: 1fr;
  }

  .header h1 {
    font-size: 24px;
  }

  .my-results h2 {
    font-size: 20px;
  }
  
  .pagination {
    flex-wrap: wrap;
  }
}
</style>
